function procesSelection(){
   var selectedJobs=getSelectedJobs();
   if(selectedJobs.length==0) {
      $('#jobActions').hide();
      $('#headerName').show();
   }
   else if(selectedJobs.length>0){
      $('#jobActions .selectnum').text('已选择' + selectedJobs.length + '个职位');
      $('#jobActions').show();
      $('#headerName').hide();
   }
}

function getSelectedJobs(property){
   var elements=$('.jobitem .check:checked').closest('.jobitem');
   var jobs=[];
   /* make sure to filter out just-trashed jobs */
   elements.not(function() { return $(this).hasClass("trashed"); }).each(function(i,element){
      if($.isArray(property)){
         var job={};
         $.each(property,function(index,prop){
            job[prop]=$(element).data(prop);
         });
         jobs.push(job);
      }else{
         var job={
            id:$(element).attr('data-id'),
            name:$(element).data('title')
         };
         if(property){
            jobs.push(job[property]);
         }else{
            jobs.push(job);
         }
      }
   });
   return jobs; 
}

jQuery(document).ready(function($) {
    $.ajaxSetup({cache: false});
    procesSelection();
    
    function scrollmessage_p() {
      var scrolltops = $(window).scrollTop();
      var searchheight = $(".highsearch_wrap").height()+25;
      var ishidden = $("#jobActions.p_batchaction_inner").is(":hidden");
      if (scrolltops >= (searchheight+3)) {
         if(!ishidden) {
            $("#jobActions.p_batchaction_inner").addClass("needfixed");
            $("#jobneeds.hr_position_indexinner").addClass("needmargintop");
         }
         else {
            $("#jobActions.p_batchaction_inner").removeClass("needfixed");
            $("#jobneeds.hr_position_indexinner").removeClass("needmargintop");
         }
      }
      else {
         $("#jobActions.p_batchaction_inner").removeClass("needfixed");
         $("#jobneeds.hr_position_indexinner").removeClass("needmargintop");
      } 
   }
   
   $(window).scroll(function(){
      scrollmessage_p(); 
   });

    $('#headerWrap').on('click', '.selectAll', function(){
       /*jobPosition allSelect status match with simpleSelect status*/
       var rowDiv = $("div.jobitem.hr_position_each");
       if($(this).prop('checked')){
          // Check all
          $('.jobitem .check, #headerWrap .selectAll').prop('checked', true);
          rowDiv.addClass('selected');
       }else{
          // Uncheck all
          $('.jobitem .check, #headerWrap .selectAll').prop('checked', false);
          rowDiv.removeClass('selected');
       }
       procesSelection();
       scrollmessage_p();
    });
    
    $('.jobitem').on('click', '.check', function(){
       /*jobPosition allSelect status match with simpleSelect status*/
       var rowDiv = $(this).closest("div.jobitem.hr_position_each");
       if($(this).prop('checked')){
          // Check
          $(this).prop('checked', true);
          rowDiv.addClass('selected');
          var selectedCount=$("[type='checkbox'].check:checked").length;
          if (selectedCount == $("[type='checkbox'].check").length) {
             $('#headerWrap .selectAll').prop('checked', true);
          }
       }else{
          // Uncheck
          $('#headerWrap .selectAll').prop('checked', false);
          $(this).prop('checked', false);
          rowDiv.removeClass('selected');
       }
       
       procesSelection();
       scrollmessage_p();
    });
    
    $('#jobActions').on('click', '.save', function(event){
       var jobs=getSelectedJobs('id');
       event.preventDefault();
       JobList.do_save(jobs);
       return false;
    });
    
    $('#jobActions').on('click', '.unsave', function(event){
       var jobs=getSelectedJobs('id');
       event.preventDefault();
       JobList.do_unsave(jobs);
       return false;
    });
    
    $('#jobActions').on('click', '.settop', function(event) {
       var jobs=getSelectedJobs('id');
       event.preventDefault();
       JobList.do_settop(jobs);
       return false;
    });
    
    $('#jobActions').on('click', '.unsettop', function(event) {
       var jobs=getSelectedJobs('id');
       event.preventDefault();
       JobList.do_unsettop(jobs);
       return false;
    });

    $('#jobActions').on('click', '.renew', function(event) {
       var jobs=getSelectedJobs('id');
       event.preventDefault();
       JobList.do_renew(jobs,'renewjobs');
       return false;
    });

    $('#jobActions').on('click', '.autorenew', function(event) {
       var jobs=getSelectedJobs('id');
       event.preventDefault();
       JobList.do_renew(jobs,'autorenewjobs');
       return false;
    });
    
    $('#jobActions').on('click', '.delete', function(event) {
       var jobs=getSelectedJobs('id');
       event.preventDefault();
       if(typeof(storageGet('iknow_jobtrash_tips')) != 'undefined') {
          JobList.do_trash(jobs);
       } else {
          showJobTrashConfirm(function(){
             JobList.do_trash(jobs);
          });
       }
       return false;
    });
    
    $('#jobActions').on('click', '.restore', function(event) {
       var jobs=getSelectedJobs('id');
       event.preventDefault();
       JobList.do_restore(jobs);
       return false;
    });
    
    $('#jobActions').on('click', '.infolder', function(event) {
       var jobs=getSelectedJobs('id');
       event.preventDefault();
       JobList.do_infolder(jobs);
       return false;
    });
    
    $(document).on('click', '.closediv', function(){
       $(this).closest('.popup').hide();
   });

    $(document).on('click','#saveautorenewjobs',function(){
       var syncsources = [];
       var wuyoujobs = $('input[name=jobids_51job]').val();
       if(wuyoujobs.length > 0)
          syncsources.push('51job');
       var zhilian = $('input[name=jobids_zhilian]').val();
       if(zhilian.length > 0)
          syncsources.push('zhilian');
       var lagou = $('input[name=jobids_lagou]').val();
       if(lagou.length > 0)
          syncsources.push('lagou');
       var jiancai = $('input[name=jobids_jiancai]').val();
       if(jiancai.length > 0)
          syncsources.push('jiancai');
       if(syncsources.length>0){
          $("#autorenewdialog").modal('hide');
          $('#renew_syncto').data('syncto', syncsources.join(','));
          showRenewSyncPopup(function(){
             var autosetresult = $('#renew_syncto').data('autosetresult');
             if(autosetresult.length<=0)
                return;
             var sources = autosetresult.split(',');
             var target = $('.autorenew_dialog');
             showAutoResultDialog(target,'open',sources,'autorenewjobs');
             $('#renew_syncto').data('autosetresult','')
          });
       }else{
          showMessagePanel('所选职位不可设置自动刷新！', $(this), true, {placement:'right'});
       }
    });

    var showRenewSyncPopup = function(callback) {
       if($('#renew_syncto').length > 0) {
          var syncto = $('#renew_syncto').data('syncto');
          var autosetresult = $('#renew_syncto').data('autosetresult');
          if(syncto.length <= 0) {
             if(callback) callback();
          }else{
             syncto =  syncto.split(',');
             var source = syncto.shift();
             $('#renew_syncto').data('syncto', syncto.join(','));
             var jobids = $('input[name="jobids_'+source+'"]').val().split(',');
             var loginstatus = $('input[name="jobids_'+source+'"]').data('loginstatus');
             var data = {
                   type: 'autorenewjobs_'+source, 
                   source: 'autorenewjobs',
                   ids: JSON.stringify(jobids),
                   syncsource : source
                };
             $.ajax({
                type: "POST",
                url: OC.filePath('jobposition', 'ajax', 'savejobgroup.php'),
                data: data,
                success: function(result){
                   if (result.status == 'success') {
                      var data = {
                            type: source,
                            syncaction: 'autorenewjobs'
                         };
                      if(loginstatus == 0){
                         startSync(source, data, function(result) {
                            if(result === true){
                               autosetresult = autosetresult?autosetresult.split(','):[];
                               autosetresult.push(source);
                               $('#renew_syncto').data('autosetresult', autosetresult.join(','));
                            }
                            setTimeout(function() { showRenewSyncPopup(callback); }, 1);
                         }, function() { 
                            // nothing to track login 
                         }, function() {
                            // Do nothing here
                         });
                      }else{
                         $.ajax({
                            type: "POST",
                            url: setautoaction,
                            data: {type: source,syncaction: 'autorenewjobs'},
                            dataType: 'json',
                            success: function(result) {
                               if(result.success == 'success'){
                                  autosetresult = autosetresult?autosetresult.split(','):[];
                                  autosetresult.push(source);
                                  $('#renew_syncto').data('autosetresult', autosetresult.join(','));
                                  showRenewSyncPopup(callback); 
                               }else if(result.error == 'error'){
                                  showMessagePanel('网络异常，请刷新重试！', $(this), true, {placement:'right'});
                               }
                            }
                         });
                      }
                   }
                }
             });
          }
       }
    }

    $(document).on('click','#autorenewdialog .cancel',function(){
       $('#autorenewdialog').modal('hide');
    });
});
